package com.pactera.base.commons.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.pactera.base.commons.entity.BaseEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @author wangrui
 * mybatisPlus代码生成
 */
public class MybatisCodeGenerator {

    private static Logger log = LoggerFactory.getLogger(MybatisCodeGenerator.class);

    /**
     * 核心类，所有操作配置都围绕该类展开
     */
    private static final AutoGenerator MPG = new AutoGenerator();
    /**
     * 获取项目目录
     */
    private static final String PROJECT_PATH = System.getProperty("user.dir");
    /**
     * 项目基础包
     */
    private static final String PACKAGE_URL = "com.pactera.base";

    private MybatisCodeGenerator(){

    }
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        log.info("请输入{} :",tip);
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + "模块名" + "！");
    }


    public static void main(String[] args) {
        //数据库连接配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/dbgirl?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("123456");
        MPG.setDataSource(dataSourceConfig);
        //公用的一些配置，一看就懂的就不加注释了。
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(PROJECT_PATH + "/src/main/java");
        globalConfig.setAuthor("wang rui");
        globalConfig.setSwagger2(true);
        //日期类型的字段使用哪个类型，默认是 java8的 日期类型，此处改为 java.util.date
        globalConfig.setDateType(DateType.ONLY_DATE);
        //是否覆盖 已存在文件，默认 false 不覆盖
        globalConfig.setFileOverride(true);
        //mapper.xml 是否生成 ResultMap，默认 false 不生成
        globalConfig.setBaseResultMap(true);
        //mapper.xml 是否生成 ColumnList，默认 false 不生成
        globalConfig.setBaseColumnList(true);
        //是否生成完成后打开资源管理器
        globalConfig.setOpen(false);
        MPG.setGlobalConfig(globalConfig);

        PackageConfig pc = new PackageConfig();
        pc.setParent(PACKAGE_URL);
        pc.setModuleName(scanner("模块名"));
        MPG.setPackageInfo(pc);

        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude(scanner("表名,多个以英文逗号分隔"));
        //此处配置为 下划线转驼峰命名
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //配置父类
        strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
        strategy.setSuperServiceImplClass(ServiceImpl.class);
        strategy.setSuperServiceClass(IService.class);
        strategy.setSuperEntityClass(BaseEntity.class);
        strategy.setSuperEntityColumns("id","create_time","update_time","create_user","update_user","delete_status");
        MPG.setStrategy(strategy);

        InjectionConfig in = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        in.setFileOutConfigList(CollectionUtil.newArrayList(new FileOutConfig("/templates/mapper.xml.btl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义mapper xml输出目录
                return PROJECT_PATH + "/src/main/resources/mybatis/mapper/" + tableInfo.getMapperName()  + StringPool.DOT_XML;
            }
        }));
        MPG.setCfg(in);
        TemplateConfig templateConfig = new TemplateConfig();
        //关闭默认的mapper xml生成
        templateConfig.setXml(null);
        MPG.setTemplate(templateConfig);
        //使用beetl模版引擎
        MPG.setTemplateEngine(new BeetlTemplateEngine());
        MPG.execute();
    }

}
